package com.ai.web.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.h2.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ai.web.app.AndroidPushNotification;
import com.ai.web.app.IosPushNotification;
import com.ai.web.cache.Constants;
import com.ai.web.http.HttpUtil;
import com.ai.web.schedule.WorkOrdersQueue;
import com.ai.web.sendreq.ICachUtil;
import com.ai.web.service.AppPushLogService;
import com.ai.web.service.AppUserService;
import com.ai.web.service.CommentRepairService;
import com.ai.web.service.ICashDeviceService;
import com.ai.web.service.RepairService;
import com.ai.web.service.WxUserService;
import com.ai.web.util.Utils;
import com.ai.web.util.WorkStatus;
import com.ai.web.vo.AppPushLogV;
import com.ai.web.vo.AppUserV;
import com.ai.web.vo.CommentRepairV;
import com.ai.web.vo.ICashSerialNumReturnMsgV;
import com.ai.web.vo.QueryData;
import com.ai.web.vo.RepairV;
import com.ai.web.vo.ResultModel;
import com.ai.web.vo.WxUserV;
import com.ai.web.weixin.WeixinContext;
import com.tiny.persistence.domain.WxUser;
/**
 * 设备报修
* @ClassName: RepairController 
* @Description: TODO 
* @author:  
* @date: 2014年3月24日
*
 */
@Controller
@RequestMapping("/repair")
public class RepairController extends BaseController {
    

    private static Logger logger = Logger.getLogger(RepairController.class);
    @Autowired
    private RepairService repairService;
    @Autowired
    private WxUserService wxUserService;
    @Autowired
    private AppUserService appUserService;
    @Autowired
    private AppPushLogService appPushLogService;
    @Autowired
    private CommentRepairService commentRepairService;
    @Autowired
	private ICashDeviceService iCashDeviceService;
    
    @RequestMapping(value = "/list")
    public String list(@RequestParam HashMap<String, Object> paramMap, Model model) {
        logger.info("hello......test"+paramMap);
        model.addAttribute("status", paramMap.get("param"));
        return "repair/repair_list";
    }
    
    @RequestMapping(value = "/query", produces = "application/json")
    @ResponseBody
    public QueryData query(@RequestParam HashMap<String, Object> paramMap)
            throws Exception {
        
        Map<String, Object> conditionMap = buildCondition(paramMap);
        logger.info("---- " + conditionMap);
        
        QueryData qd = repairService.queryListAndCount(conditionMap);
   	 	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<RepairV> dataList = new ArrayList<RepairV>();
        for(Object object:qd.getDataList()){
        	RepairV repairV = (RepairV)object;
        	if(repairV.getExpectedRepairTime() != null){
                repairV.setExpectedRepairTimeStr(sdf.format(repairV.getExpectedRepairTime()));
        	}
        	if(repairV.getPlanRepairTime() != null){
                repairV.setPlanRepairTimeStr(sdf.format(repairV.getPlanRepairTime()));
        	}
        	if(repairV.getRepairDate() != null){
                repairV.setRepairDateStr(sdf.format(repairV.getRepairDate()));
        	}
        	if(repairV.getMaintenanceTimeStart() != null){
                repairV.setMaintenanceTimeStartStr(sdf.format(repairV.getMaintenanceTimeStart()));	
        	}
        	if(repairV.getMaintenanceTimeEnd() != null){
                repairV.setMaintenanceTimeEndStr(sdf.format(repairV.getMaintenanceTimeEnd()));	
        	}
        	if(repairV.getCreateTime() != null){
                repairV.setCreateTimeStr(sdf.format(repairV.getCreateTime()));	
        	}
        	repairV.setStatusStr(WorkStatus.getName(repairV.getStatus()));
            dataList.add(repairV);
            
        }
        qd.setDataList(dataList);
        return qd;
    }
    
    /**
     * 导出
     * @param paramMap
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/exportExcel")
    public void exportExcel(@RequestParam HashMap<String, Object> paramMap)
            throws Exception {
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        logger.info("---- " + paramMap);
        //工单号,机器序列号,工单状态,故障信息,设备地址,设备所属机构,报修人,报修人手机号码,报修人单位,维修人,维修人手机号码,联系人,联系人手机号码,期望维修时间,预约维修时间,报修日期,维护开始时间,完成时间,创建时间,备注
        String[] keys = {"id","serialNumber","status","faultInfo","machineAddress","orgName","bankUser","bankUserPhone","bankUserCompany","maintenanceUser","maintenancePhone","contact","contactPhone","expectedRepairTime","planRepairTime","repairDate","maintenanceTimeStart","maintenanceTimeEnd","createTime","maintenanceRemark"};
        List<RepairV> dataList = (List<RepairV>)repairService.queryList(paramMap);
        List<Map<String, String>> dataSet = new ArrayList<Map<String,String>>();
        //列头
        Map<String, String> map = new HashMap<String, String>();
    	map.put("id","工单号");
    	map.put("serialNumber","机器序列号");
    	map.put("status","工单状态");
    	map.put("faultInfo","故障信息");
    	map.put("machineAddress","设备地址");
    	map.put("orgName","设备所属机构");
    	map.put("bankUser","报修人");
    	map.put("bankUserPhone","报修人手机号码");
    	map.put("bankUserCompany","报修人单位");
    	map.put("maintenanceUser","维修人");
    	map.put("maintenancePhone","维修人手机号码");
    	map.put("contact","联系人");
    	map.put("contactPhone","联系人手机号码");
    	map.put("expectedRepairTime","期望维修时间");
    	map.put("planRepairTime","预约维修时间");
    	map.put("repairDate","报修日期");
    	map.put("maintenanceTimeStart","维护开始时间");
    	map.put("maintenanceTimeEnd","完成时间");
    	map.put("createTime","创建时间");
    	map.put("maintenanceRemark","备注");
    	dataSet.add(map);
        
        for(RepairV v : dataList){
        	map = new HashMap<String, String>();
        	map.put("id",v.getId()+"");
        	map.put("serialNumber",v.getSerialNumber());
        	map.put("status",WorkStatus.getName(v.getStatus()));
        	map.put("faultInfo",v.getFaultInfo());
        	map.put("machineAddress",v.getMachineAddress());
        	map.put("orgName",v.getOrgName());
        	map.put("bankUser",v.getBankUser());
        	map.put("bankUserPhone",v.getBankUserPhone());
        	map.put("bankUserCompany",v.getBankUserCompany());
        	map.put("maintenanceUser",v.getMaintenanceUser());
        	map.put("maintenancePhone",v.getMaintenancePhone());
        	map.put("contact",v.getContact());
        	map.put("contactPhone",v.getContactPhone());
        	map.put("maintenanceRemark",v.getMaintenanceRemark());
        	if(v.getExpectedRepairTime() != null){
        		map.put("expectedRepairTime",sdf.format(v.getExpectedRepairTime()));
        	}else{
        		map.put("expectedRepairTime","");
        	}
        	if(v.getPlanRepairTime() != null){
        		map.put("planRepairTime",sdf.format(v.getPlanRepairTime()));
        	}else{
        		map.put("planRepairTime","");
        	}
        	if(v.getRepairDate() != null){
        		map.put("repairDate",sdf.format(v.getRepairDate()));
        	}else{
        		map.put("repairDate","");
        	}
        	if(v.getMaintenanceTimeStart() != null){
        		map.put("maintenanceTimeStart",sdf.format(v.getMaintenanceTimeStart()));
        	}else{
        		map.put("maintenanceTimeStart","");
        	}
        	if(v.getMaintenanceTimeEnd() != null){
        		map.put("maintenanceTimeEnd",sdf.format(v.getMaintenanceTimeEnd()));
        	}else{
        		map.put("maintenanceTimeEnd","");
        	}
        	if(v.getCreateTime() != null){
        		map.put("createTime",sdf.format(v.getCreateTime()));
        	}else{
        		map.put("createTime","");
        	}
        	dataSet.add(map);
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmm");
        exportXls(dataSet, keys, "repair"+df.format(new Date())+".xls");
    }
    
    @RequestMapping(value = "/new")
    public String newRepair(Model model) {
        
        RepairV RepairV = new RepairV();
        model.addAttribute(RepairV);
        
        return "repair/repair_template";
    }
    @RequestMapping(value = "/view/{id}")
    public String view(@PathVariable("id") int id, Model model)
            throws Exception {
        
        RepairV repairV = repairService.getRepair(id);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if(repairV.getRepairDate() != null){
            repairV.setRepairDateStr(sdf.format(repairV.getRepairDate()));
    	}
        if(repairV.getExpectedRepairTime() != null){
            repairV.setExpectedRepairTimeStr(sdf.format(repairV.getExpectedRepairTime()));
    	}
        if(repairV.getMaintenanceTimeStart() != null){
            repairV.setMaintenanceTimeStartStr(sdf.format(repairV.getMaintenanceTimeStart()));	
    	}
    	if(repairV.getMaintenanceTimeEnd() != null){
            repairV.setMaintenanceTimeEndStr(sdf.format(repairV.getMaintenanceTimeEnd()));	
    	}
        logger.info("----- getUser:" + repairV);
        
        model.addAttribute(repairV);
        
        return "repair/repair_info";
    }
    @RequestMapping(value = "/update/{id}")
    public String updateRepair(@PathVariable("id") int id, Model model)
            throws Exception {
        
        RepairV repairV = repairService.getRepair(id);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if(repairV.getRepairDate() != null){
            repairV.setRepairDateStr(sdf.format(repairV.getRepairDate()));
    	}
        if(repairV.getMaintenanceTimeStart() != null){
            repairV.setMaintenanceTimeStartStr(sdf.format(repairV.getMaintenanceTimeStart()));	
    	}
    	if(repairV.getMaintenanceTimeEnd() != null){
            repairV.setMaintenanceTimeEndStr(sdf.format(repairV.getMaintenanceTimeEnd()));	
    	}
        if(repairV.getExpectedRepairTime() != null){
            repairV.setExpectedRepairTimeStr(sdf.format(repairV.getExpectedRepairTime()));
        }
        logger.info("----- getUser:" + repairV);
        
        model.addAttribute(repairV);
        
        return "repair/repair_template";
    }
    
    @RequestMapping(value = "/save", produces = "application/json")
    @ResponseBody
    public ResultModel saveRepair(RepairV repairV) throws Exception {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        logger.info("-----save:" + repairV);
    	RepairV v = null;
    	if(repairV.getId() != 0){
    		v = repairService.getRepair(repairV.getId());
    	}
        ICashSerialNumReturnMsgV iCashSerialNumReturnMsgV = ICachUtil
                .verificationSerialNumber(repairV.getSerialNumber());
        ResultModel rm = new ResultModel();
        if (iCashSerialNumReturnMsgV.getResult() == 0) {
            rm.setFailCode();
            rm.setMsg("该设备序列号不存在");
            return rm;
        }
        String  manufacturer = iCashSerialNumReturnMsgV.getManufacturerV().getBrandName();
        String	model = iCashSerialNumReturnMsgV.getModelV().getModelName();
        String	machineAddress = iCashSerialNumReturnMsgV.getMachineAddress();
        String	maintenancePhone = iCashSerialNumReturnMsgV.getMaintenancePhone();
        String  maintenanceUser = iCashSerialNumReturnMsgV.getMaintenanceUser();
        String  contact = iCashSerialNumReturnMsgV.getContact();
        String  contactPhone = iCashSerialNumReturnMsgV.getContactPhone();
        String orgId = iCashSerialNumReturnMsgV.getOrgId();
        String orgName = iCashSerialNumReturnMsgV.getOrgName();
        repairV.setManufacturer(manufacturer);
        repairV.setMaintenancePhone(maintenancePhone);
        repairV.setMaintenanceUser(maintenanceUser);
        repairV.setContact(contact);
        repairV.setContactPhone(contactPhone);
        repairV.setModel(model);
        repairV.setMachineAddress(machineAddress);
        repairV.setOrgId(orgId);
        repairV.setOrgName(orgName);
    	if(v==null) {
    		//new
            if(!StringUtils.isNullOrEmpty(repairV.getRepairDateStr())){
                repairV.setRepairDate(sdf.parse(repairV.getRepairDateStr()));
            }
            if(!StringUtils.isNullOrEmpty(repairV.getMaintenanceTimeStartStr())){
                repairV.setMaintenanceTimeStart(sdf.parse(repairV.getMaintenanceTimeStartStr()));
            }
            if(!StringUtils.isNullOrEmpty(repairV.getMaintenanceTimeEndStr())){
                repairV.setMaintenanceTimeEnd(sdf.parse(repairV.getMaintenanceTimeEndStr()));
            }
            if(!StringUtils.isNullOrEmpty(repairV.getExpectedRepairTimeStr())){
                repairV.setExpectedRepairTime(sdf.parse(repairV.getExpectedRepairTimeStr()));
            }
            repairV.setCreateTime(new Date());
            rm = repairService.saveRepair(repairV);
    	}else {
            v.setBankUser(repairV.getBankUser());
            v.setBankUserPhone(repairV.getBankUserPhone());
            v.setContact(repairV.getContact());
            v.setContactPhone(repairV.getContactPhone());
            v.setFaultInfo(repairV.getFaultInfo());
            v.setSerialNumber(repairV.getSerialNumber());
            v.setMaintenancePhone(repairV.getMaintenancePhone());
            v.setMaintenanceUser(repairV.getMaintenanceUser());
            v.setMachineAddress(repairV.getMachineAddress());
            if(!StringUtils.isNullOrEmpty(repairV.getExpectedRepairTimeStr())){
                v.setExpectedRepairTime(sdf.parse(repairV.getExpectedRepairTimeStr()));
            }
            rm = repairService.saveRepair(v);
    	}
    	//放在待下发工单缓存
        WorkOrdersQueue.offer((RepairV)rm.getData());
        return rm;
    }
    
    @RequestMapping(value = "/delete", produces = "application/json")
    @ResponseBody
    public ResultModel deleteRepair(@RequestParam String delIds)
            throws Exception {
        
        System.out.println(delIds);
        
        List<Integer> userIds = getDeleteIds(delIds);
        ResultModel rm = repairService.deleteRepairs(userIds);
        
        return rm;
    }
    
    @SuppressWarnings("rawtypes")
	@RequestMapping(value = "/getCountByStatus", produces = "application/json")
    @ResponseBody
    public List getCountByStatus()
            throws Exception {
    	return repairService.getCountByStatus();
    }
    
    @RequestMapping(value = "/status/template/{status}")
    public String statusTemplate(@PathVariable("status")int status, Model model) {
    	model.addAttribute("status", status);     
        return "repair/repair_status_list";
    }
    
    @RequestMapping(value = "/status/list/{status}", produces = "application/json")
    @ResponseBody
    public QueryData query(@PathVariable("status")int status, @RequestParam HashMap<String, Object> paramMap)
            throws Exception {
        
        Map<String, Object> conditionMap = buildCondition(paramMap);
        conditionMap.put("status", status);
        logger.info("---- " + conditionMap);
        
        QueryData qd = repairService.queryListAndCount(conditionMap);
   	 	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<RepairV> dataList = new ArrayList<RepairV>();
        for(Object object:qd.getDataList()){
        	RepairV repairV = (RepairV)object;
        	if(repairV.getRepairDate() != null){
                repairV.setRepairDateStr(sdf.format(repairV.getRepairDate()));
        	}
        	if(repairV.getMaintenanceTimeStart() != null){
                repairV.setMaintenanceTimeStartStr(sdf.format(repairV.getMaintenanceTimeStart()));	
        	}
        	if(repairV.getMaintenanceTimeEnd() != null){
                repairV.setMaintenanceTimeEndStr(sdf.format(repairV.getMaintenanceTimeEnd()));	
        	}
        	repairV.setStatusStr(WorkStatus.getName(repairV.getStatus()));
            dataList.add(repairV);
            
        }
        qd.setDataList(dataList);
        return qd;
    }
    
	/**
     * 生成工单
     * @param 微信提交的参数：清分机的序列号，期望维修时间，联系人电话，故障信息,维修人电话
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/weixin/generateByManuallyEnter", method=RequestMethod.POST)
    public ResultModel generateWorkOrders(@RequestParam String serialNumber, @RequestParam String expectedRepairTime,
    		@RequestParam String faultInfo, @RequestParam String openId, @RequestParam String breakCode) throws Exception {
    	ICashSerialNumReturnMsgV iCashSerialNumReturnMsgV = ICachUtil
				.verificationSerialNumber(serialNumber);
    	ResultModel rm = new ResultModel();
		if (iCashSerialNumReturnMsgV.getResult() == 0) {
			rm.setFailCode();
			rm.setMsg("该设备序列号不存在");
			return rm;
		}
    	String  manufacturer = iCashSerialNumReturnMsgV.getManufacturerV().getBrandName();
    	String	model = iCashSerialNumReturnMsgV.getModelV().getModelName();
    	String	machineAddress = iCashSerialNumReturnMsgV.getMachineAddress();
    	String	maintenancePhone = iCashSerialNumReturnMsgV.getMaintenancePhone();
    	String  maintenanceUser = iCashSerialNumReturnMsgV.getMaintenanceUser();
    	String  contact = iCashSerialNumReturnMsgV.getContact();
    	String  contactPhone = iCashSerialNumReturnMsgV.getContactPhone();
    	String orgId = iCashSerialNumReturnMsgV.getOrgId();
    	String orgName = iCashSerialNumReturnMsgV.getOrgName();
        RepairV repairV = new RepairV();
   	 	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        
        //生成工单
        if(!StringUtils.isNullOrEmpty(expectedRepairTime)){
            repairV.setExpectedRepairTime(sdf.parse(expectedRepairTime));
        }
        repairV.setSerialNumber(serialNumber);
        //repairV.setBankUserPhone(bankUserPhone);
        repairV.setManufacturer(manufacturer);
        repairV.setMaintenancePhone(maintenancePhone);
        repairV.setMaintenanceUser(maintenanceUser);
        repairV.setFaultInfo(faultInfo);
        repairV.setContact(contact);
        repairV.setContactPhone(contactPhone);
        repairV.setModel(model);
        repairV.setMachineAddress(machineAddress);
        repairV.setRepairDate(new Date());
        repairV.setOrgId(orgId);
        repairV.setOrgName(orgName);
        repairV.setBreakCode(breakCode);
       // repairV.setAuthUser(authUser);
        WxUser wxUser = wxUserService.getByOpenId(openId);
        logger.info("wxUser：" + wxUser);
        if(wxUser != null){
	        repairV.setBankUser(wxUser.getUsername());
	        repairV.setBankUserPhone(wxUser.getMobilePhone());
        }
        logger.info("repairV：" + repairV);
        repairV.setCreateTime(new Date());
        rm = repairService.generateWorkOrders(repairV);
        
        //放在待下发工单缓存
        WorkOrdersQueue.offer((RepairV)rm.getData());
        
        return rm;
    }
    
    /**
     * 生成工单
     * @param 微信提交的参数：清分机的序列号，期望维修时间，联系人电话，故障信息,维修人电话
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/weixin/generate/{serialNumber}")
    public ResultModel generateWorkOrderBySerialNumber(@RequestParam(required=false) String openId, @RequestParam(required=false) String expectedRepairTime, @RequestParam String manufacturer,
    		@RequestParam String model,@RequestParam String maintenanceUser,@RequestParam String maintenancePhone,@RequestParam String machineAddress, @RequestParam String contact, 
    		@RequestParam String contactPhone, @RequestParam String faultInfo, @PathVariable("serialNumber") String serialNumber
    		,@RequestParam(required=false) String orgId, @RequestParam(required=false) String orgName) throws Exception {
        RepairV repairV = new RepairV();
   	 	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //生成工单
        if(!StringUtils.isNullOrEmpty(expectedRepairTime)){
        	try{
        		repairV.setExpectedRepairTime(sdf.parse(expectedRepairTime));
        	}catch(Exception e){
        		sdf = new SimpleDateFormat("yyyyMMdd");
        		try{
        			repairV.setExpectedRepairTime(sdf.parse(expectedRepairTime));
        		}catch(Exception e1){
        			sdf = new SimpleDateFormat("yyyy-MM-dd");
        			repairV.setExpectedRepairTime(sdf.parse(expectedRepairTime));
        		}
        	}
        }
        repairV.setSerialNumber(serialNumber);
        //repairV.setBankUserPhone(bankUserPhone);
        repairV.setManufacturer(manufacturer);
        repairV.setMaintenancePhone(maintenancePhone);
        repairV.setMaintenanceUser(maintenanceUser);
        repairV.setFaultInfo(faultInfo);
        repairV.setContact(contact);
        repairV.setContactPhone(contactPhone);
        repairV.setModel(model);
        repairV.setMachineAddress(machineAddress);
        repairV.setRepairDate(new Date());
        repairV.setCreateTime(new Date());
        repairV.setOrgId(orgId);
        repairV.setOrgName(orgName);
       // repairV.setAuthUser(authUser);
        if(!Utils.isEmpty(openId)){
        	WxUser wxUser = wxUserService.getByOpenId(openId);
            logger.info("wxUser：" + wxUser);
            if(wxUser != null){
    	        repairV.setBankUser(wxUser.getUsername());
    	        repairV.setBankUserPhone(wxUser.getMobilePhone());
    	        repairV.setBankUserCompany(wxUser.getCompany());
            } else {
            	repairV.setBankUser(contact);
            	repairV.setBankUserPhone(contactPhone);
            	repairV.setBankUserCompany("--");
            }
        } else {
        	repairV.setBankUser(contact);
        	repairV.setBankUserPhone(contactPhone);
        	repairV.setBankUserCompany("--");
        }
        logger.info("repairV：" + repairV);
        ResultModel rm = repairService.generateWorkOrders(repairV);
        
        //放在待下发工单缓存
        WorkOrdersQueue.offer((RepairV)rm.getData());
        
        return rm;
    }
    
    /**
     * 派发工单
     * @param 
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/manualSend/{id}")
    public ResultModel sendWorkOrders(@PathVariable("id") int id) throws Exception {
    	ResultModel rm = new ResultModel();
    	RepairV repairV = repairService.getRepair(id);
    	WxUserV wxUser = wxUserService.getByMobilePhone(repairV.getBankUserPhone());
    	//维护人员的电话号码
    	String maintenancePhone = repairV.getMaintenancePhone();
    	if(maintenancePhone!=null) {
    		AppUserV appUser = appUserService.getAppUserByPhone(maintenancePhone);
    		if(appUser!=null) {
    			//如果状态不是未派发，直接丢弃
				if(repairV.getStatus()==WorkStatus.NEW.getValue()) {
	    			//手动派发工单
	    			rm = manualSend(id, rm, wxUser, repairV, appUser);
				} else {
					rm.setFailCode();
					rm.setMsg("工单已经自动派发");
				}
    		} else {
    			rm.setFailCode();
				rm.setMsg("该工单维护人员手机没有做绑定，派发失败");
    		}
    	}
        return rm;
    }

    
    
    /**
     * 确认工单
     * @param 微信提交参数：工单id、预约维修时间
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/weixin/confirm/{id}")
    public ResultModel confirmWorkOrders(@PathVariable("id") int id, @RequestParam String planRepairTimeStr, @RequestParam String maintenanceRemark) throws Exception {
        
        //维护人员确认该工单，并填写预约维修时间，工单变成已确认工单
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        RepairV repairV = repairService.getRepair(id);
        if(!StringUtils.isNullOrEmpty(planRepairTimeStr)){
            repairV.setPlanRepairTime(sdf.parse(planRepairTimeStr));
        }
        //修改工单状态:已确认
        repairV.setStatus(WorkStatus.CONFIRM.getValue());
        repairV.setMaintenanceRemark(maintenanceRemark);
        ResultModel rm = repairService.generateWorkOrders(repairV);
        if(rm.getStatusCode() == 20011011 && !Utils.isEmpty(repairV.getBankUserPhone())){
        	WxUserV wxUserV = wxUserService.getByMobilePhone(repairV.getBankUserPhone());
        	if(wxUserV != null){
	        	String serviceUrl = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token="+WeixinContext.access_token;
	    		String content = "工单:"+repairV.getFaultInfo()+", 设备编号："+repairV.getSerialNumber()+", 已经确认";
	        	String body = "{\"touser\":\""+wxUserV.getOpenId()+"\",\"msgtype\":\"text\",\"text\": {\"content\":\""+content+"\"}}";
	        	logger.info("feedbackWorkOrders url:"+serviceUrl+"  body:"+body);
	        	System.out.println("feedbackWorkOrders url:"+serviceUrl+"  body:"+body);
	        	try {
	    			HttpUtil.httpRequest(serviceUrl, "POST", null, body);
	    		} catch (Exception e) {
	    			logger.error(e.getMessage(), e);
	    		}
        	}
        }
        return rm;
    }
    
    /**
     * 反馈工单
     * @param 微信提交参数：工单id、反馈信息
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/weixin/feedback/{id}")
    public ResultModel feedbackWorkOrders(@PathVariable("id") int id, @RequestParam String feedbackInfo) throws Exception {
        
        //进行工单反馈，并填写反馈信息，工单变为已反馈工单。
        
        @SuppressWarnings("unused")
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        RepairV repairV = repairService.getRepair(id);
        repairV.setFeedbackInfo(feedbackInfo);
        //修改工单状态:待确认
        repairV.setStatus(WorkStatus.WAITCONFIRM.getValue());
        ResultModel rm = repairService.generateWorkOrders(repairV);
        System.out.println("auditWxUser ResultModel:"+rm);
        if(rm.getStatusCode() == 20011011 && !Utils.isEmpty(repairV.getBankUserPhone())){
        	WxUserV wxUserV = wxUserService.getByMobilePhone(repairV.getBankUserPhone());
        	if(wxUserV != null){
	        	String serviceUrl = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token="+WeixinContext.access_token;
	    		String content = "工单:"+repairV.getFaultInfo()+", 设备编号："+repairV.getSerialNumber()+",反馈信息:"+ feedbackInfo;
	        	String body = "{\"touser\":\""+wxUserV.getOpenId()+"\",\"msgtype\":\"text\",\"text\": {\"content\":\""+content+"\"}}";
	        	logger.info("feedbackWorkOrders url:"+serviceUrl+"  body:"+body);
	        	System.out.println("feedbackWorkOrders url:"+serviceUrl+"  body:"+body);
	        	try {
	    			HttpUtil.httpRequest(serviceUrl, "POST", null, body);
	    		} catch (Exception e) {
	    			logger.error(e.getMessage(), e);
	    		}
        	}
        }
        return rm;
    }
    
    /**
     * 设备维护开始
     * @param 微信提交参数：工单id、维护备注信息、工单维护开始时间
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/weixin/startMaintenance/{id}")
    public ResultModel startMaintenance(@PathVariable("id") int id, @RequestParam String maintenanceRemark) throws Exception {
        
        //维护人员对设备进行维护，填写工单的维护开始时间，完成后填写备注信息，提交完成，系统自动填入完成时间。
        RepairV repairV = repairService.getRepair(id);
        repairV.setMaintenanceTimeStart(new Date());
        repairV.setMaintenanceRemark(maintenanceRemark);
        //修改工单状态:维修中
        repairV.setStatus(WorkStatus.MAINTAIN.getValue());
        ResultModel rm = repairService.generateWorkOrders(repairV);
        if(rm.getStatusCode() == 20011011 && !Utils.isEmpty(repairV.getBankUserPhone())){
        	WxUserV wxUserV = wxUserService.getByMobilePhone(repairV.getBankUserPhone());
        	if(wxUserV != null){
	        	String serviceUrl = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token="+WeixinContext.access_token;
	    		String content = "工单:"+repairV.getFaultInfo()+", 设备编号："+repairV.getSerialNumber()+", 已经开始维护";
	        	String body = "{\"touser\":\""+wxUserV.getOpenId()+"\",\"msgtype\":\"text\",\"text\": {\"content\":\""+content+"\"}}";
	        	logger.info("feedbackWorkOrders url:"+serviceUrl+"  body:"+body);
	        	System.out.println("feedbackWorkOrders url:"+serviceUrl+"  body:"+body);
	        	try {
	    			HttpUtil.httpRequest(serviceUrl, "POST", null, body);
	    		} catch (Exception e) {
	    			logger.error(e.getMessage(), e);
	    		}
        	}
        }
        return rm;
    }
    
    /**
     * 设备维护完成
     * @param 微信提交参数：工单id、维护备注信息、工单维护完成时间
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/weixin/complateMaintenance/{id}")
    public ResultModel complateMaintenance(@PathVariable("id") int id, @RequestParam String maintenanceRemark) throws Exception {
        
        //维护人员对设备进行维护，填写工单的维护开始时间，完成后填写备注信息，提交完成，系统自动填入完成时间。
        RepairV repairV = repairService.getRepair(id);
        repairV.setMaintenanceTimeEnd(new Date());
        repairV.setMaintenanceRemark(maintenanceRemark);
        //修改工单状态:已完成
        repairV.setStatus(WorkStatus.FINISHED.getValue());
        ResultModel rm = repairService.generateWorkOrders(repairV);
        if(rm.getStatusCode() == 20011011 && !Utils.isEmpty(repairV.getBankUserPhone())){
        	WxUserV wxUserV = wxUserService.getByMobilePhone(repairV.getBankUserPhone());
        	if(wxUserV != null){
	        	String serviceUrl = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token="+WeixinContext.access_token;
	    		String content = "工单:"+repairV.getFaultInfo()+", 设备编号："+repairV.getSerialNumber()+", 已经完成维护";
	        	String body = "{\"touser\":\""+wxUserV.getOpenId()+"\",\"msgtype\":\"text\",\"text\": {\"content\":\""+content+"\"}}";
	        	logger.info("feedbackWorkOrders url:"+serviceUrl+"  body:"+body);
	        	System.out.println("feedbackWorkOrders url:"+serviceUrl+"  body:"+body);
	        	try {
	    			HttpUtil.httpRequest(serviceUrl, "POST", null, body);
	    		} catch (Exception e) {
	    			logger.error(e.getMessage(), e);
	    		}
        	}
        }
        return rm;
    }
    
    /**
     * 设备报修评价
     * @param 微信提交参数：工单id、维护备注信息、工单维护完成时间
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/weixin/comment/{id}")
    public ResultModel commentMaintenance(@PathVariable("id") int id, @RequestParam int useSatValue, @RequestParam int customerServiceSatValue, @RequestParam String comment, @RequestParam String openId) throws Exception {
        RepairV repairV = repairService.getRepair(id);
        repairV.setStatus(WorkStatus.COMMENT.getValue());
        repairService.generateWorkOrders(repairV);
        CommentRepairV commentRepairV = new CommentRepairV();
        commentRepairV.setRepairId(id);
        commentRepairV.setCommenterName(repairV.getBankUser());
        commentRepairV.setMobilePhone(repairV.getBankUserPhone());
        commentRepairV.setUseSat(useSatValue);
        commentRepairV.setCustomerServiceSat(customerServiceSatValue);
        commentRepairV.setComment(comment);
        return commentRepairService.saveCommentRepair(commentRepairV);
    }
    
    /**
     * 手动派发工单
     * @param id
     * @param rm
     * @param wxUser 
     * @param repairV
     * @param wxUser
     * @param appUser
     * @throws InterruptedException
     * @throws Exception
     */
	private ResultModel manualSend(int id, ResultModel rm, WxUserV wxUser, RepairV repairV,
			 AppUserV appUser) throws InterruptedException,
			Exception {
		//派发工单
		long channelId = appUser.getPushChannelId();
		String userId = appUser.getPushUserId();
		String msgTitle = "派发工单";        		
		String msgDesc = "派发工单,机器序列号："+ repairV.getSerialNumber();
		Map<String, String> msgCustomMap = new HashMap<String, String>();
		String url = Constants.SERVER_HOST + "/weixin/repair/select/"+id;
		if(wxUser!=null && !Utils.isEmpty(wxUser.getOpenId())){
			url += "?openId="+wxUser.getOpenId();
		}else{
			url += "?openId="+Constants.DEFAULT_OPEN_ID;
		}
		msgCustomMap.put("req", url);
		msgCustomMap.put("repairId", String.valueOf(repairV.getId()));
		//先APP推送，记录推送结果，总共重试3次，间隔30秒
		int count = 0;
		boolean sendFlag = false;
		
		//修改工单状态:先改状态为已派发，失败了再改回未派发，防止跟自动派发重复派单
	    repairV.setStatus(WorkStatus.DISTRIBUTE.getValue());
	    rm = repairService.saveRepair(repairV);
	    
		while(count<3 && !sendFlag) {
			if(appUser.getDeviceType()==1) {
				sendFlag = AndroidPushNotification.pushMsg(channelId, userId, msgTitle, msgDesc, msgCustomMap);
			}else {
				sendFlag = IosPushNotification.pushMsg(channelId, userId, msgTitle, msgDesc, msgCustomMap);
			}
			if (sendFlag) {
				break;
			} else {
				count++;
				Thread.sleep(30000);
			}
		}
		//如果推送失败，记录一条失败记录，产生一个系统提醒
		if(!sendFlag) {
			logger.info("推送失败,尝试推送次数{"+count+"}");
			//派发失败，改回状态:未派发
			repairV.setStatus(WorkStatus.NEW.getValue());
		    rm = repairService.saveRepair(repairV);
			rm.setFailCode();
		}else {
			logger.info("推送已成功,推送次数{"+count+"}");
		    rm.setSuccessCode();
		}
		//记录推送结果
		AppPushLogV appPushLogV = new AppPushLogV();
		appPushLogV.setChannelId(String.valueOf(channelId));
		appPushLogV.setUserId(userId);
		appPushLogV.setMsgTitle(msgTitle);
		appPushLogV.setMsgDesc(msgDesc + " --- " + repairV.getFaultInfo());
		appPushLogV.setUrl(url);
		appPushLogV.setStatusCode(rm.getStatusCode());
		appPushLogService.saveAppPushLog(appPushLogV);
		return rm;
	}
}
